package com.young.redis.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringUtils;

/**
 * Redission 配置
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/11/20
 */
@PropertySource(name = "META-INF/redis.properties", value = "classpath:META-INF/redis.properties", ignoreResourceNotFound = false, encoding = "GBK")
@Configuration
public class RedissonConfig {
    @Bean(destroyMethod = "shutdown")
    public RedissonClient singleRedis(@Value("${spring.redis.address}") String address,
                                      @Value("${spring.redis.port}") String port,
                                      @Value("${spring.redis.timeout}") int timeout,
                                      @Value("${spring.redis.password}") String password,
                                      @Value("${spring.redis.database}") int database
    ) {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress("redis://" + address + ":" + port);
        singleServerConfig.setTimeout(timeout);
        singleServerConfig.setDatabase(database);

        /**
         * 字符集设置很重要
         *  {@link org.redisson.config.Config#Config(org.redisson.config.Config)}
         */
        config.setCodec(new org.redisson.client.codec.StringCodec());
        if (!StringUtils.isEmpty(password)) {
            singleServerConfig.setPassword(password);
        }
        return Redisson.create(config);
    }
}